package com.dony.shop.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dony.common.utils.SecurityUtils;
import com.dony.common.utils.StringUtils;
import com.dony.shop.domain.*;
import com.dony.shop.mapper.DiscountMapper;
import com.dony.shop.service.*;
import com.dony.shop.util.ShopeeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author sundw
 * @date 2022-08-30
 */
@Slf4j
@Service
public class DiscountServiceImpl extends ServiceImpl<DiscountMapper, Discount> implements IDiscountService {

    @Autowired
    ShopeeUtil shopeeUtil;
    @Resource
    IPublishTaskService publishTaskService;
    @Resource
    IItemModelService itemModelService;
    @Resource
    IShopeeMerchantService merchantService;
    @Resource
    IPriceConfigService priceConfigService;
    @Resource
    IShopeeShopService shopService;
    @Resource
    ThreadPoolTaskExecutor executor;

    @Override
    public boolean syncByMerchantId(Discount discount) {
        executor.execute(() -> {
            syncDiscountByMerchantId(discount.getMerchantId());
        });
        return true;
    }

    private boolean syncDiscountByMerchantId(Long merchantId) {
        if (merchantId == null) {
            log.error("商户不能为空！");
            return false;
        }
        List<ShopeeShop> shops = shopService.getPublishShopListByMerchant(merchantId);
        Long tenantId = merchantService.getTenantByMerchant(merchantId);
        //this.remove(new QueryWrapper<Discount>().eq("merchant_id", merchantId));
        shops.forEach(shop -> {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("discount_status", "ongoing");
            paramMap.put("page_no", 1);
            paramMap.put("page_size", 100);
            JSONObject response = shopeeUtil.shopGetHandler("/api/v2/discount/get_discount_list", shop.getShopId(), paramMap);
            if (response == null) {
                log.warn("{}店铺的请求，没有数据返回！", shop.getShopId());
                return;
            }
            List<JSONObject> discountJoList = (List<JSONObject>) response.get("discount_list");
            if (discountJoList == null) {
                log.warn("{}店铺没有设置折扣！", shop.getShopId());
                return;
            }
            //将本店铺所有的折扣设置为过期
            LambdaUpdateWrapper<Discount> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Discount::getShopId, shop.getShopId())
                    .set(Discount::getStatus, "expired");
            this.update(updateWrapper);

            List<Discount> discountList = discountJoList.stream().map(discountJo -> {
                Discount dis = new Discount();
                dis.setShopId(shop.getShopId());
                dis.setMerchantId(merchantId);
                dis.setTenantId(tenantId);
                dis.setRegion(shop.getRegion());
                dis.setStatus(discountJo.getString("status"));
                dis.setDiscountName(discountJo.getString("discount_name"));
                dis.setStartTime(new Date(discountJo.getLong("start_time") * 1000L));
                dis.setDiscountId(discountJo.getLong("discount_id"));
                dis.setSource(discountJo.getInteger("source"));
                dis.setEndTime(new Date(discountJo.getLong("end_time") * 1000L));
                return dis;
            }).collect(Collectors.toList());
            this.saveOrUpdateBatch(discountList);

            //过期的折扣取消发布功能
            LambdaUpdateWrapper<Discount> delWrapper = new LambdaUpdateWrapper<>();
            delWrapper.eq(Discount::getShopId, shop.getShopId())
                    .eq(Discount::getStatus, "expired")
                    .set(Discount::getIsPublish, "0");
            this.update(delWrapper);
        });
        return true;
    }

    @Override
    public Boolean addDiscountAll(Long merchantId) {
        return null;
    }

    @Override
    public Boolean addDiscountAll(Long[] publishId) {
        return null;
    }

    @Override
    public Boolean addDiscount(Long itemId) {


        return null;
    }

    public Boolean addDiscount(PublishTask publishTask) {
        Discount discount = this.getOne(new QueryWrapper<Discount>().eq("shop_id", publishTask.getShopId()).eq("is_publish", 1));
        if (discount == null) {
            log.error("折扣信息设置错误，店铺ID：{}", publishTask.getShopId());
            return false;
        }
        PriceConfig priceConfig = priceConfigService.getOne(new QueryWrapper<PriceConfig>().eq("merchant_id", publishTask.getMerchantId()).eq("status", 1));
        if (priceConfig == null) {
            log.error("价格参数信息设置错误，商户ID：{}", publishTask.getMerchantId());
            return false;
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("discount_id", discount.getDiscountId());

        //封装商品
        List<Map<String, Object>> items = new ArrayList<>();

        Map<String, Object> item = new HashMap<>();
        item.put("item_id", publishTask.getItemId());
        List<ItemModel> modelList = itemModelService.list(new QueryWrapper<ItemModel>().eq("item_id", publishTask.getItemId()));
        List<Map<String, Object>> models = modelList.stream().map(itemModel -> {
            Map<String, Object> model = new HashMap<>();
            model.put("model_id", itemModel.getModelId());
            //越南特殊处理
            if (StringUtils.equals("VN", publishTask.getRegion())) {
                if (itemModel.getOriginalPrice() <= 800000) {
                    model.put("model_promotion_price", itemModel.getOriginalPrice() * 80 / 100);
                } else {
                    model.put("model_promotion_price", itemModel.getOriginalPrice() - 1000);
                }
            } else {
                model.put("model_promotion_price", itemModel.getOriginalPrice() * priceConfig.getDiscount() / 100);
            }
            return model;
        }).collect(Collectors.toList());
        item.put("model_list", models);
        //越南修改文本

        item.put("purchase_limit", 0);
        items.add(item);
        paramMap.put("item_list", items);
        JSONObject response = shopeeUtil.shopPostHandler("/api/v2/discount/add_discount_item", publishTask.getShopId(), paramMap);
        if (response == null) {
            return false;
        }
        publishTask.setStatus(2);
        publishTaskService.updateById(publishTask);
        Integer count = response.getInteger("count");
        log.info("添加折扣成功：{}个商品规格", count);
        return true;
    }

    @Override
    public Boolean addPublishDiscount(Long[] publishTaskIds) {
        //线程池异步执行添加折扣的方法
        executor.execute(() -> {
            List<PublishTask> publishTasks = publishTaskService.sycnStatus(publishTaskIds);
            publishTasks.stream()
                    .filter(t -> t.getStatus() == 1 && StringUtils.equals("NORMAL", t.getItemStatus()))
                    .forEach(task -> this.addDiscount(task));
        });
        return true;
    }

    //暂时不用
    @Override
    public Boolean addAllDiscount(Long merchantId) {
        //线程池异步执行添加折扣的方法
        executor.execute(() -> {
            List<PublishTask> publishTasks = publishTaskService.list(new QueryWrapper<PublishTask>().eq("merchant_id", merchantId).eq("status", 1));
            publishTasks.forEach(task -> this.addDiscount(task));
        });
        return true;
    }

    @Override
    public List<Discount> listDiscount(Discount discount) {
        QueryWrapper<Discount> queryWrapper = new QueryWrapper<>();

//        if (discount != null && discount.getMerchantId() != null) {
        if (discount != null) {
            queryWrapper.eq("merchant_id", discount.getMerchantId());
        }
        queryWrapper.eq("status", "ongoing");
        queryWrapper.eq("tenant_id", SecurityUtils.getDeptId());
        queryWrapper.orderByAsc("region");
        return list(queryWrapper);
    }

    @Override
    public Boolean changeDiscountPrice(Long shopId, Long itemId, Map<Float, Float> priceMap) {
        //查询数据库中的折扣
        Discount discount = this.getOne(new QueryWrapper<Discount>().eq("shop_id", shopId).eq("is_publish", 1));
        if (discount == null) {
            log.error("当前店铺的折扣信息过期！店铺Id:{}", shopId);
            return false;
        }
        //封装商品
        Map<String, Object> paramMap = new HashMap<>();
        List<Map<String, Object>> items = new ArrayList<>();
        Map<String, Object> item = new HashMap<>();
        item.put("item_id", itemId);
        List<ItemModel> modelList = itemModelService.list(new QueryWrapper<ItemModel>().eq("item_id", itemId));
        List<Map<String, Object>> models = modelList.stream().map(itemModel -> {
            Map<String, Object> model = new HashMap<>();
            model.put("model_id", itemModel.getModelId());
            model.put("model_promotion_price", priceMap.get(itemModelService.getGlobalModelPrice(itemModel.getItemId(), itemModel.getTierIndex())));
            return model;
        }).collect(Collectors.toList());
        item.put("model_list", models);
        items.add(item);
        paramMap.put("item_list", items);
        paramMap.put("discount_id", discount.getDiscountId());
        JSONObject response = shopeeUtil.shopPostHandler("/api/v2/discount/update_discount_item", shopId, paramMap);
        return response != null;
    }

    @Override
    public Boolean changeItemPrice(Item item, Map<Float, Float> priceMap) {
        //查询数据库中的折扣
        Discount discount = this.getOne(new QueryWrapper<Discount>().eq("shop_id", item.getShopId()).eq("is_publish", 1));
        if (discount == null) {
            log.error("当前店铺的折扣信息过期！店铺Id:{}", item.getShopId());
            return false;
        }
        //封装商品
        Map<String, Object> paramMap = new HashMap<>();
        List<Map<String, Object>> items = new ArrayList<>();
        Map<String, Object> it = new HashMap<>();
        it.put("item_id", item.getItemId());
        List<ItemModel> modelList = itemModelService.list(new QueryWrapper<ItemModel>().eq("item_id", item.getItemId()));
        List<Map<String, Object>> models = modelList.stream().map(itemModel -> {
            Map<String, Object> model = new HashMap<>();
            model.put("model_id", itemModel.getModelId());
            model.put("model_promotion_price", priceMap.get(itemModel.getOriginalPrice()));
            return model;
        }).collect(Collectors.toList());
        it.put("model_list", models);
        items.add(it);
        paramMap.put("item_list", items);
        paramMap.put("discount_id", discount.getDiscountId());
        JSONObject response = shopeeUtil.shopPostHandler("/api/v2/discount/update_discount_item", item.getShopId(), paramMap);
        return response != null;
    }


    public Discount getDiscount(Long shopId) {
        return this.getOne(new QueryWrapper<Discount>().eq("shop_id", shopId).eq("is_publish", 1));
    }

}
